<?php

namespace app\home\logic;

use think\Model;
use think\db;

class BorrowTender extends Model
{
    /**
     * 添加投标
     *
     * @param array $data
     * @return array
     */
    public static function AddTender($data = [])
    {

        $result = self::CheckTender([
            "borrow_nid" => $data['borrow_nid'],
            "user_id" => $data['user_id'],
            "coupon_users_id" => $data['coupon_users_id'],
            'account' => $data['account']
        ]);
        if ($result['code'] != 1) {
            return $result;
        }
        $borrow_result = $result['result'];
        $coupon_users_id = $data['coupon_users_id'];
        unset($data['coupon_users_id']);

        //判断金额是否正确【不可改】
        if (!isset($data['account']) || !is_numeric($data['account']) || $data['account'] <= 0) {
            return ['code' => 0, 'msg' => '金额不正确'];
        } elseif ($data['account'] % 100 != 0) {
            return ['code' => 0, 'msg' => '投标金额为100的整数倍'];
        }

        //支付密码不正确
        $user = model('user')->getUser([
            'user_id' => $data['user_id']
        ]);
        if ($user['paypassword'] == '') {
            return ['code' => 0, 'msg' => '请先设置交易密码"'];
        }
        if (session('tb_paypwd_error_count') > 2) {
            return ['code' => 0, 'msg' => '交易密码错误3次，请重置交易密码'];
        }
        if ((!isset($data['auto_type']) || $data['auto_type'] != 'auto') && md5($data['paypassword']) != $user['paypassword']) {
            session('tb_paypwd_error_count', (session('tb_paypwd_error_count') ? session('tb_paypwd_error_count') + 1 : 1));
            return ['code' => 0, 'msg' => '交易密码不正确'];
        }
        $auto_tender = false;
        if (isset($data['auto_type']) && $data['auto_type'] == 'auto') {
            $auto_tender = true;
        }
        unset($data['valicode']);
        unset($data['auto_status']);
        unset($data['auto_type']);
        unset($data['paypassword']);

        //$_SESSION["valicode"] = "";
        //判断类型是否正确
        /* if ($borrow_result['borrow_password'] != "" && md5($data["borrow_password"]) != $borrow_result['borrow_password']) {
            return "borrow_password_error";
        } */
        unset($data['borrow_password']);


        //判断是否大于投资金额【可改】
        $tender_account_all = self::GetUserTenderAccount(array("user_id" => $data["user_id"], "borrow_nid" => $data['borrow_nid']));
        if ($data['account'] > $borrow_result['tender_account_max'] && $borrow_result['tender_account_max'] > 0) {
            return ['code' => 0, 'msg' => '此标最大投标金额不能大于' . $borrow_result['tender_account_max']];
        } elseif ($tender_account_all + $data['account'] > $borrow_result['tender_account_max'] && $borrow_result['tender_account_max'] > 0) {
            $tender_account = $borrow_result['tender_account_max'] - $tender_account_all;
            return ['code' => 0, 'msg' => "您已经投标了{$tender_account_all},最大投标总金额不能大于{$borrow_result['tender_account_max']}，你最多还能投资{$tender_account}"];
        } else {
            $data['account_tender'] = $data['account'];

            //判断投资的金额是否大于待借的金额
            if ($borrow_result['borrow_account_wait'] < $data['account']) {
                $data['account'] = $borrow_result['borrow_account_wait'];
            } elseif ($data['account'] < $borrow_result['tender_account_min']) {   //判断是否小于最小投资金额【可改】
                return ['code' => 0, 'msg' => "最小的投资金额不能小于{$borrow_result['tender_account_min']}。"];
            }

            //判断可用金额是否足够投资
            $account_result = model('account')->getOne(array("user_id" => $data['user_id']));//获取当前用户的余额
            if ($account_result['balance'] < $data['account']) {
                return ['code' => 0, 'msg' => '余额不足'];
            }
            //续投奖（ 给可提现的金额投资为续投奖  续投奖 投资金额（必须是可提现的金额）的千分之一）
//            if($account_result['balance_frost'] < $data['account']) {
//                $is_xt = true;
//            }
        }

        $_tender_result = db('borrow_tender')->where(['borrow_nid' => $data['borrow_nid']])->sum('account');
        if ($_tender_result >= $borrow_result["account"]) {
            return ['code' => 0, 'msg' => '此标已满标'];
        }

        //开启事务
        Db::startTrans();

        //添加投资的借款信息
        $tender_id = model('borrow_tender')->add($data);
        if ($tender_id > 0) {

            if ($coupon_users_id != "") {
                $coupon_use_re = model('coupon', 'logic')->UseCouponUsers([
                    "id" => $coupon_users_id,
                    "user_id" => $data['user_id'],
                    "borrow_nid" => $data['borrow_nid'],
                    "borrow_tender_id" => $tender_id,
                    "account" => $data['account']
                ]);
                if (!$coupon_use_re) {
                    Db::rollback();
                    return ['code' => 0, '优惠券有误'];
                }
            }

            if ($auto_tender) {
                model('borrow_autolog')->add([
                    'borrow_nid' => $data['borrow_nid'],
                    'user_id' => $data["user_id"],
                    'account' => $data['account'],
                    'remark' => $tender_id
                ]);
            }
            //判断投资的金额是否大于待借的金额
            $_result_b = db('borrow')->field('borrow_account_wait')->where(['borrow_nid' => $data['borrow_nid']])->find();
            if ($_result_b["borrow_account_wait"] - $data['account'] < 0) {
                Db::rollback();
                return ['code' => 0, '投资金额已满'];
            }

            $prefix = config('database.prefix');
            //1，更新借款的信息
            $sql = "update  `{$prefix}borrow` set borrow_account_yes=borrow_account_yes+{$data['account']},borrow_account_wait=borrow_account_wait-{$data['account']},borrow_account_scale=TRUNCATE((borrow_account_yes/account)*100,2),tender_times=tender_times+1  where borrow_nid='{$data['borrow_nid']}'";
            $ex = db()->execute($sql);
            if (!$ex) {
                Db::rollback();
                return ['code' => 0, '投资失败'];
            }

            //2，扣除可用金额
            $url = url('project/detail?nid=' . $borrow_result['borrow_nid']);
            $borrow_url = "<a href=/invest/a{$borrow_result['borrow_nid']}.html target=_blank >{$borrow_result['name']}</a>";
            $log_info["user_id"] = $data["user_id"];//操作用户id
            $log_info["account_web_status"] = 0;//
            $log_info["account_user_status"] = 0;//
            $log_info["nid"] = "tender_frost_" . $data['user_id'] . "_" . $data['borrow_nid'] . "_" . $tender_id;
            $log_info["borrow_nid"] = $data['borrow_nid'];//收入
            $log_info["code"] = "borrow";//
            $log_info["code_type"] = "tender";//
            $log_info["code_nid"] = $tender_id;//
            $log_info["money"] = $data['account'];//操作金额
            $log_info["income"] = 0;//收入
            $log_info["expend"] = 0;//支出
            $log_info["balance_cash"] = 0;//可提现金额
            $log_info["balance_frost"] = -$data['account'];//不可提现金额
            $log_info["frost"] = $data['account'];//冻结金额
            $log_info["await"] = 0;//待收金额
            $log_info["repay"] = 0;//待还金额
            $log_info["type"] = "tender";//类型
            $log_info["to_userid"] = $borrow_result['user_id'];//付给谁
            if ($auto_tender) {
                $log_info["remark"] = "自动投标[{$borrow_url}]所冻结资金";//备注
            } else {
                $log_info["remark"] = "投标[{$borrow_url}]所冻结资金";//备注
            }
            $result = model('account', 'logic')->AddLog($log_info);
            if ($result['code'] != 1) {
                Db::rollback();
                return $result;
            }

            //3，更新统计信息
            model('borrow_count', 'logic')->UpdateBorrowCount(array("user_id" => $data['user_id'], "borrow_nid" => $data['borrow_nid'], "nid" => "tender_frost_" . $data['user_id'] . "_" . $data['borrow_nid'] . "_" . $tender_id, "tender_times" => 1, "tender_account" => $data['account'], "tender_frost_account" => $data['account']));

            //4，提醒设置 投资人
            $borrow_url = "<a href=/invest/a{$borrow_result['borrow_nid']}.html target=_blank>{$borrow_result['name']}</a>";
            $remind['nid'] = "tender";
            $remind['remind_nid'] = "tender_" . $data['user_id'] . "_" . $tender_id;
            $remind['code'] = "invest";
            $remind['article_id'] = $tender_id;
            $remind['receive_userid'] = $data['user_id'];
            $remind['title'] = "成功投资[{$borrow_result['name']}]";
            $remind['content'] = "您成功投资了{$borrow_url}，请等待管理员审核";
            model('remind', 'logic')->sendRemind($remind);

            //5，提醒设置 借款人
            $borrow_url = "<a href=/invest/a{$borrow_result['borrow_nid']}.html target=_blank>{$borrow_result['name']}</a>";
            $remind['nid'] = "borrow_tender";
            $remind['remind_nid'] = "borrow_tender_" . $borrow_result['user_id'] . "_" . $tender_id;
            $remind['code'] = "borrow";
            $remind['article_id'] = $data["user_id"];
            $remind['receive_userid'] = $borrow_result['user_id'];
            $remind['title'] = "借款标[{$borrow_result['name']}]有人投资";
            $remind['content'] = "您的借款标{$borrow_url}有人投资。";
            model('remind', 'logic')->sendRemind($remind);

            //短信提醒
            //$user_log["user_id"] = $data['user_id'];
            //$user_log["type"] = "tender_success";
            //$user_log["smstype"] = "sms";
            //$user_log["user_id"] = $data['user_id'];
            //$user_log['to_userid'] = $borrow_result['user_id'];
            //$user_log['account'] = $data['account'];
            //$user_log['borrow_nid'] = $data['borrow_nid'];
            //model('sms', 'logic')->sendsSms($user_log);
            Db::commit();

            $result = model('fuyh5', 'logic')->freezeAction([
                'rem' => '',
                'cust_no' => $user['username'],
                'amt' => $data['account'],
                'mchnt_txn_ssn' => 'app.xy' . date('YmdHis', time()),
            ]);

            //预期收益
            $_equal["account"] = $data['account_tender'];
            $_equal["period"] = $borrow_result["borrow_period"];
            $_equal["style"] = $borrow_result["borrow_style"];
            $_equal["apr"] = $borrow_result["borrow_apr"];
            $_equal["borrow_nid"] = $borrow_result['borrow_nid'];
            $_equal["type"] = "all";
            $equal_result = model('borrow_calculate', 'logic')->GetType($_equal);
            $interest_total = $equal_result['interest_total'];

            $return_data = ['code' => 1, 'msg' => '投资成功!', 'data' => [
                'tender_id' => $tender_id,
                'name' => $borrow_result['name'],
                'nid' => $borrow_result['borrow_nid'],
                'apr' => $borrow_result['borrow_apr'],
                'period' => $borrow_result['borrow_period'] . ($borrow_result['borrow_type'] == 'day' ? "天" : '个月'),
                'money' => $data['account_tender'],
                'interest' => $interest_total,
                'coupon_award' => 0,
                'coupon_name' => ''
            ]];

            if ($coupon_users_id != "" && $coupon_use_re) {
                if ($coupon_use_re['style'] == 0) {
                    $return_data['data']['coupon_award'] = $coupon_use_re['money'];
                } elseif ($coupon_use_re['style'] == 1) {
                    $_equal["apr"] = $coupon_use_re["interest"];
                    $coupon_result = model('borrow_calculate', 'logic')->GetType($_equal);
                    $return_data['data']['coupon_award'] = $coupon_result["interest_total"];
                }
                $return_data['data']['coupon_name'] = $coupon_use_re["name"];
            }

            return $return_data;
        } else {
            return ['code' => 0, 'msg' => '投资失败'];
        }
    }

    //获取用户的总投资额，可以是全部的，也可以单独的某个标
    static function GetUserTenderAccount($data)
    {
        $where = [];
        if (isset($data['user_id'])) {
            $where ['user_id'] = $data['user_id'];
        }
        if (isset($data['borrow_nid'])) {
            $where ['borrow_nid'] = $data['borrow_nid'];
        }
        $account_all = db('borrow_tender')->where($where)->sum('account');
        return $account_all ?: 0;
    }


    /**
     * 检查是否可以投资
     *
     * @param array $data
     * @return Boolen
     */

    public static function CheckTender($data = array())
    {
        //第一步，判断borrow_nid是否为空
        if (!isset($data['borrow_nid'])) {
            return ['code' => 0, 'msg' => '参数有误!'];
        }

        //第二步，判断是否存在借款标
        $borrow_result = model('borrow', 'logic')->GetOne(["borrow_nid" => $data['borrow_nid']]);
        if (!$borrow_result) {
            return ['code' => 0, 'msg' => '标的不存在!'];
        }

        //第三步，判断账号是否锁定
        //if ($_G['user_result']['islock'] == 1) {
        //    return "tender_user_lock";
        //}

        //第五步，判断是否已经通过初审审核【不可改】
        if (!isset($borrow_result['verify_time']) || $borrow_result['status'] != "1") {
            return ['code' => 0, 'msg' => '该标不可投，请刷新后重试'];
        }

        //判断是否满标
        if ($borrow_result['account'] <= $borrow_result['borrow_account_yes']) {
            return ['code' => 0, 'msg' => '已满标'];
        }

        //借款人不能自己投资
        if ($borrow_result['user_id'] == $data['user_id']) {
            return ['code' => 0, 'msg' => '不能投资自己的标'];
        }
        //新手标
        if ($borrow_result['tiro_status'] == 1) {
            $tendersRes = self::GetTenderList(array("user_id" => $data['user_id'], "page" => 1, "epage" => 1000));
            $isToubiaocount = 0;
            if (count($tendersRes) > 0) {
                foreach ($tendersRes as $key => $value) {
                    //撤标和流标不算入在内
                    if ($borrow_result['status'] == 6 || ($borrow_result['status'] == 1 && $borrow_result['borrow_status'] == 1 && $borrow_result['borrow_end_time'] < time() && $borrow_result['borrow_account_wait'] > 0)) {
                        $isToubiaocount++;
                    }
                }
                if (count($tendersRes) != $isToubiaocount) {
                    return ['code' => 0, 'msg' => '此标只允许未投资过的用户投资'];
                }
            }
            if (intval($data['account']) > 10000) {
                return ['code' => 0, 'msg' => '新手专享投资限额为10000元'];
            }
        }
        if (isset($borrow_result['begin_time']) && strtotime($borrow_result['begin_time']) > time()) {
            return ['code' => 0, 'msg' => '此标未到投标开始时间'];
        }

        if ($borrow_result['status'] == 1 && $borrow_result['borrow_end_time'] < time()) {
            return ['code' => 0, 'msg' => '此标已过期'];
        }

        //输入金额 选好券 点击提交时 标可投金额已经不符合红包 时  需要这个处理
        if (isset($data['coupon_users_id'])) {
            $coupon_result = db('coupon_users')->field('b.min')->alias('a')->join('__COUPON__ b', 'b.id = a.coupon_id', 'LEFT')
                ->where(['a.user_id' => $data['user_id'], 'a.id' => $data['coupon_users_id']])->find();
            if ($coupon_result && floatval($coupon_result['min']) > $borrow_result['borrow_account_wait']) {
                return ['code' => 0, 'msg' => '该优惠券不能使用'];
            }
        }
        return ['code' => 1, 'result' => $borrow_result];
    }


    /**
     * 获取borrow_nid下金额投资最多的记录
     * @param array $data
     */
    static function GetTenderMax($data = array())
    {
        global $mysql;
        if (isset($data['borrow_nid']) == "") {
            return "tender_borrow_nid_empty";
        }
        $sql = "select user_id,sum(account)as total from `{borrow_tender}` where borrow_nid='{$data['borrow_nid']}' group by user_id order by total desc, addtime asc limit 1";

//		$sql = "select * from `{borrow_tender}` where borrow_nid='{$data['borrow_nid']}' order by total desc, addtime asc limit 1";

        $result = $mysql->db_fetch_array($sql);
        return $result;
    }

    /**
     * 最后一笔投标
     */
    static function GetTenderLatest($data = array())
    {
        global $mysql;
        if (isset($data['borrow_nid']) == "") {
            return "tender_borrow_nid_empty";
        }
        $sql = "select * from `{borrow_tender}` where borrow_nid='{$data['borrow_nid']}'order by addtime desc, id desc limit 1";
        $result = $mysql->db_fetch_array($sql);
        return $result;
    }

    static function GetStatistics()
    {
        global $mysql;
        $cache_time = CACHE_LTIME * 2;

        //日排行
        $sql = "SELECT p1.user_id, SUM(account) AS accounts,p2.username FROM `{borrow_tender}` as p1
 				left join `{users}`  AS p2 ON p1.user_id=p2.user_id
				WHERE  p1.addtime>=" . strtotime(date("Y-m-d")) . " and p1.addtime <" . strtotime(date("Y-m-d", strtotime("+1 day"))) . " 
				GROUP BY p1.user_id ORDER BY accounts DESC  limit 10";
        $dList = $mysql->db_fetch_arrays($sql, $cache_time);

        //日加权排行
        $sql = "SELECT p1.user_id, SUM(p1.account*p3.borrow_period) AS accounts,p2.username FROM `{borrow_tender}` as p1
 				left join `{users}`  AS p2 ON p1.user_id=p2.user_id
 				left join `{borrow}`  AS p3 ON p1.borrow_nid=p3.borrow_nid
				WHERE  p1.addtime>=" . strtotime(date("Y-m-d")) . " and p1.addtime <" . strtotime(date("Y-m-d", strtotime("+1 day"))) . " and p3.borrow_type !='day' and p3.borrow_type !='second'
				GROUP BY p1.user_id ORDER BY accounts DESC  limit 10";
        $dqList = $mysql->db_fetch_arrays($sql, $cache_time);


        //当前日期
        $sdefaultDate = date("Y-m-d");

        //周排行

        $first = 1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期

        $w = date('w', strtotime($sdefaultDate)); //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
        $week_start = strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days');
        $week_start_string = date("Y-m-d", $week_start);
        $week_end = strtotime("$week_start_string +7 days");
        $sql = "SELECT p1.user_id, SUM(account) AS accounts,p2.username FROM `{borrow_tender}` as p1 
				left join `{users}`  AS p2 ON p1.user_id=p2.user_id
				WHERE  p1.addtime>=" . $week_start . " and p1.addtime <" . $week_end . " 
				GROUP BY p1.user_id ORDER BY accounts DESC  limit 10";
        $wList = $mysql->db_fetch_arrays($sql, $cache_time);

        //周加权排行
        $sql = "SELECT p1.user_id, SUM(p1.account*p3.borrow_period) AS accounts,p2.username FROM `{borrow_tender}` as p1 
				left join `{users}`  AS p2 ON p1.user_id=p2.user_id
				left join `{borrow}`  AS p3 ON p1.borrow_nid=p3.borrow_nid
				WHERE  p1.addtime>=" . $week_start . " and p1.addtime <" . $week_end . " and p3.borrow_type !='day' and p3.borrow_type !='second'
				GROUP BY p1.user_id ORDER BY accounts DESC  limit 10";
        $wqList = $mysql->db_fetch_arrays($sql, $cache_time);

        //月排行
        $firstday = strtotime(date("Y-m-01", strtotime($sdefaultDate)));
        $firstday_string = date("Y-m-d", $firstday);
        $lastday = strtotime(date("Y-m-d", strtotime("$firstday_string +1 month")));

        $sql = "SELECT p1.user_id, SUM(account) AS accounts,p2.username FROM `{borrow_tender}` as p1 
				left join `{users}`  AS p2 ON p1.user_id=p2.user_id
				WHERE  p1.addtime>=" . $firstday . " and p1.addtime <" . $lastday . "
				GROUP BY p1.user_id ORDER BY accounts DESC  limit 10";
        $mList = $mysql->db_fetch_arrays($sql, $cache_time);

        //月加权排行
        $sql = "SELECT p1.user_id, SUM(p1.account*p3.borrow_period) AS accounts,p2.username FROM `{borrow_tender}`  AS p1
				left join `{users}`  AS p2 ON p1.user_id=p2.user_id
				left join `{borrow}`  AS p3 ON p1.borrow_nid=p3.borrow_nid
				WHERE p1.addtime>=" . $firstday . " and p1.addtime <" . $lastday . " and p3.borrow_type !='day' and p3.borrow_type !='second' 
				GROUP BY p1.user_id ORDER BY accounts DESC  limit 10";
        $qList = $mysql->db_fetch_arrays($sql, $cache_time);

        //总排行
        $sql = "SELECT p1.user_id, SUM(account) AS accounts,p2.username FROM `{borrow_tender}` as p1 
				left join `{users}`  AS p2 ON p1.user_id=p2.user_id
                GROUP BY p1.user_id ORDER BY accounts DESC  limit 10";
        $nList = $mysql->db_fetch_arrays($sql, $cache_time);

        //总加权排行
        $sql = "SELECT p1.user_id, SUM(p1.account*p3.borrow_period) AS accounts,p2.username FROM `{borrow_tender}` as p1 
				left join `{users}`  AS p2 ON p1.user_id=p2.user_id
				left join `{borrow}`  AS p3 ON p1.borrow_nid=p3.borrow_nid
                WHERE p3.borrow_type !='day' and p3.borrow_type !='second' 
                GROUP BY p1.user_id ORDER BY accounts DESC  limit 10";
        $nqList = $mysql->db_fetch_arrays($sql, $cache_time);

        //年加权排行
        $year_start = strtotime(date("Y-01-01", strtotime($sdefaultDate)));
        $year_start_string = date("Y-m-d", $year_start);
        $year_end = strtotime(date("Y-m-d", strtotime("$year_start_string +1 year")));

        $sql = "SELECT p1.user_id, SUM(p1.account*p3.borrow_period) AS accounts,p2.username FROM `{borrow_tender}` as p1 
				left join `{users}`  AS p2 ON p1.user_id=p2.user_id
				left join `{borrow}`  AS p3 ON p1.borrow_nid=p3.borrow_nid
                WHERE  p1.addtime>=" . $year_start . " and p1.addtime <" . $year_end . " and p3.borrow_type !='day' and p3.borrow_type !='second' 
                GROUP BY p1.user_id ORDER BY accounts DESC  limit 10";
        $yList = $mysql->db_fetch_arrays($sql, $cache_time);

        //自动投标排序
        $sql = "SELECT p1.id,p1.user_id,p1.tender_account as account,p1.status,p2.username FROM `{borrow_auto}` AS p1
				left join `{users}` AS p2 ON p1.user_id=p2.user_id
				left join `{account}` AS p3 ON p1.user_id=p3.user_id
				WHERE p1.status='1' and p3.balance>=p1.tender_account ORDER BY p1.updatetime ASC limit 10";
        $aList = $mysql->db_fetch_arrays($sql);

        return array(
            'dList' => $dList,
            'wList' => $wList,
            'mList' => $mList,
            'nList' => $nList,
            'dqList' => $dqList,
            'wqList' => $wqList,
            'qList' => $qList,
            'nqList' => $nqList,
            'yList' => $yList,
            'aList' => $aList
        );
    }


    /**
     * 投资列表
     *
     * @return Array
     */
    static function GetTenderList($data = array())
    {
        $_sql = "where 1=1 ";
        if (isset($data['tender_nid'])) {
            $_sql .= " and p1.tender_nid='{$data['tender_nid']}'";
        }
        //ahui 0328 zhaiquan
        //判断用户id
        if (isset($data['user_id'])) {
            $_sql .= " and ((p1.change_status!=1 and p1.user_id={$data['user_id']}) or (p1.change_status=1 and p1.change_userid='{$data['user_id']}'))";
        }

        //判断借款用户
        if (isset($data['borrow_userid'])) {
            $_sql .= " and p3.user_id = {$data['borrow_userid']}";
        }
        //借款协议
        if (isset($data['tender_id']) && isset($data['borrow_id'])) {
            if ($data['tender_id'] != $data['borrow_id']) {
                $_sql .= " and p1.user_id = {$data['tender_id']}";
            }
        }

        //搜到用户名
        if (isset($data['username'])) {
            $data['username'] = urldecode($data['username']);
            $_sql .= " and p2.username like '%{$data['username']}%'";
        }

        //搜索借款名称
        if (isset($data['borrow_status'])) {
            $_sql .= " and p3.`status` in ({$data['borrow_status']})";
        }

        if (isset($data['change_status'])) {
            $_sql .= " and p1.`change_status` in  ({$data['change_status']})";
        }


        //搜索借款名称
        if (isset($data['borrow_name'])) {
            $_sql .= " and p3.`name` like '%" . urldecode($data['borrow_name']) . "%'";
        }

        //搜索借款名称
        if (isset($data['borrow_nid'])) {
            $_sql .= " and p3.`borrow_nid` = '{$data['borrow_nid']}'";
        }

        //投资类型
        if (isset($data['tender_type'])) {
            if ($data['tender_type'] == "wait") {
                $_sql .= "  and p3.`status` = 3 and ((p3.borrow_type!='roam' and p3.repay_full_status=0 and p1.recover_full_status=0) or (p3.borrow_type='roam' and p3.tender_times!=p3.repay_times))  ";
            } elseif ($data['tender_type'] == "over") {
                $_sql .= "  and p3.`status` = 3 and (p3.repay_full_status=1 or (p1.recover_times=1 and p3.borrow_type='day') or(p1.recover_times=1 and p3.borrow_type='second')) ";
            }
        }

        if (isset($data['keywords']) != "") {
            $_sql .= " and (p3.name like '%" . urldecode($data['keywords']) . "%') ";
        }

        //判断添加时间开始
        if (isset($data['dotime1'])) {
            $dotime1 = ($data['dotime1'] == "request") ? $_REQUEST['dotime1'] : $data['dotime1'];
            if (get_mktime($dotime1) != "") {
                $_sql .= " and p1.addtime > " . get_mktime($dotime1);
            }
        }

        //判断添加时间结束
        if (isset($data['dotime2'])) {
            $dotime2 = ($data['dotime2'] == "request") ? $_REQUEST['dotime2'] : $data['dotime2'];
            if (get_mktime($dotime2) != "") {
                $_sql .= " and p1.addtime < " . get_mktime($dotime2);
            }
        }

        if (isset($data['time'])) {
            switch ($data['time']) {
                case 1:
                case 3:
                case 6:
                    $_sql .= " and p1.addtime <= " . strtotime('+ ' . $data['time'] . '  months') . " and p1.addtime >= " . strtotime('-' . $data['time'] . ' months ');
                    break;
                case 7:
                    $_sql .= " and p1.addtime <= " . strtotime('+ ' . $data['time'] . '  days') . " and p1.addtime >= " . strtotime('-' . $data['time'] . ' days');
                    break;
            }
        }

        //判断借款状态
        if (isset($data['status']) != "") {
            $_sql .= " and p8.recover_status in ({$data['status']})";
        }
        //判断是否担保借款
        if (isset($data['vouch_status']) != "") {
            $_sql .= " and p3.vouch_status in ({$data['vouch_status']})";
        }

        //借款期数
        if (isset($data['borrow_period']) != "") {
            $_sql .= " and p3.borrow_period = {$data['borrow_period']}";
        }

        //借款类别
        if (isset($data['flag']) != "") {
            $_sql .= " and p3.flag = {$data['flag']}";
        }

        //借款用途
        if (isset($data['borrow_use']) != "") {
            $_sql .= " and p3.borrow_use in ({$data['borrow_use']})";
        }


        //借款用户类型
        if (isset($data['borrow_usertype']) != "") {
            $_sql .= " and p3.borrow_usertype = '{$data['borrow_usertype']}'";
        }


        //借款
        if (isset($data['borrow_style'])) {
            $_sql .= " and p3.borrow_style in ({$data['borrow_style']})";
        }
        //新手标
        if (isset($data['tiro_status'])) {
            $_sql .= " and p3.tiro_status = '{$data['tiro_status']}'";
        }

        //金额权限
        if (isset($data['account1']) != "") {
            $_sql .= " and p1.account >= {$data['account1']}";
        }
        if (isset($data['account2']) != "") {
            $_sql .= " and p1.account <= {$data['account2']}";
        }

        //排序
        if (isset($data['order']) && $data['order'] != "") {
            if ($data['order'] == "addtime" || $data['order'] == "order") {
                $_order = " order by p1.addtime desc, p1.id desc";
            } else {
                $_order = " order by p1.{$data['order']}";
            }
        } else {
            $_order = " order by p1.id desc";
        }
        $prefix = config('database.prefix');
        $_select = " p1.*,p2.username,p8.recover_status,
        p3.name as borrow_name,p3.account as borrow_account,p3.borrow_type,p3.status as borrow_status,
        p4.username as borrow_username,p3.repay_account_wait as borrow_account_wait_all,
        p3.repay_account_interest_wait as borrow_interest_wait_all,p4.user_id as borrow_userid,p3.borrow_apr,p3.borrow_apr_extra,p3.borrow_style,p3.borrow_period,p3.borrow_account_scale,p7.name as borrow_type_name,p3.verify_time as borrow_verify_time,p3.repay_last_time,p3.borrow_success_time as borrow_start_time,p6.realname,p6.card_id,p2.phone, p3.verify_time as verify_time";
        /*if(isset($data['type'])&&$data['type']=="roam"){
           $_select='DISTINCT p1.user_id,p5.realname';
       } */
        $sql = "select SELECT from `{$prefix}borrow_tender` as p1 
				 left join `{$prefix}borrow_recover` as p8 on p1.id=p8.tender_id
				 left join `{$prefix}users` as p2 on p1.user_id=p2.user_id
				 left join `{$prefix}borrow` as p3 on p1.borrow_nid=p3.borrow_nid
				 left join `{$prefix}borrow_type` as p7 on p7.nid=p3.borrow_type
				 left join `{$prefix}users` as p4 on p4.user_id=p3.user_id
                 left join `{$prefix}users_info` as p5 on p5.user_id=p1.user_id
                 left join `{$prefix}approve_realname` as p6 on p6.user_id=p1.user_id
				 SQL ORDER LIMIT
				";

        $data['page'] = !isset($data['page']) ? 1 : $data['page'];
        $data['epage'] = !isset($data['epage']) ? 10 : $data['epage'];

        //是否显示全部的信息
        if (isset($data['limit'])) {
            if ($data['limit'] != "all") {
                $_limit = "  limit " . $data['limit'];
            } else {
                $_limit = "";
            }
        } else {
            $_limit = " limit " . ($data['epage'] * ($data['page'] - 1)) . ", {$data['epage']}";
        }

        $sql = str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($_select, $_sql, $_order, $_limit), $sql);
        $list = db()->query($sql);
        foreach ($list as $key => $value) {
            $repayresult = db('borrow_repay')->where(['repay_time' => ['lt', time()], 'repay_status' => 0, 'borrow_nid' => $value['borrow_nid']])->find();
            if ($repayresult) {
                $list[$key]['change_no'] = 1;
            }
            $period_name = "个月";
            if ($value["borrow_type"] == "day") {
                $period_name = "天";
                $base = 0.5;
                $i = $value['borrow_period'] % 30;
                $day = ($value['borrow_period'] - $i) / 30;

                $day_apr = $base * ($day > 0 ? $day - 1 : 0);
            }
            $list[$key]["borrow_apr_1"] = $value["borrow_apr"];

            $list[$key]["borrow_period_name"] = $value["borrow_period"] . $period_name;

            // if ($value['borrow_type'] == "day" || $value['borrow_type'] == "roam" || $value['borrow_type'] == "second") {
            // $list[$key]['borrow_period'] = 1;
            // }
            if ($value['borrow_type'] == "roam") {
                $list[$key]['repay_last_time'] = strtotime("{$value["borrow_period"]} month", $value['addtime']);;
            }

            //借款期限
            if ($value['borrow_type'] == "roam" || $value['borrow_type'] == "day" || $value['borrow_type'] == "second") {
                $list[$key]["_borrow_period"] = 1;
            } else {
                $list[$key]["_borrow_period"] = $value["borrow_period"];
            }
            //积分
            //$list[$key]["credit"] = borrowClass::GetBorrowCredit(array("user_id" => $value['borrow_userid']));


        }
        return $list;
    }


    /**
     * 7,投资撤销，只要运用在投资人不想投的情况下可以手动的撤回，撤回需缴纳一定的
     *
     * @param Array $data = array("id"=>"投资序号","tender_nid"=>"投资标识名");
     * @return Array
     */
    public static function CancelTender($data = array())
    {
        global $mysql;
        $sql = "select * from `{borrow_tender}` where tender_nid='{$data['tender_nid']}'";
        $result = $mysql->db_fetch_array($sql);
        if ($result == false) return "borrow_tender_not_exiest";
        if ($result['tender_status'] > 0) return "borrow_tender_verify_yes";

        $sql = "update `{borrow_tender}` set status=0 where tender_nid='{$data['tender_nid']}'";
        $mysql->db_query($sql);


        return $data['tender_nid'];
    }

    //已成功的借款
    static function GetTenderBorrowList($data)
    {
        global $mysql, $_G;
        $user_id = $data['user_id'];
        $page = empty($data['page']) ? 1 : $data['page'];
        $epage = empty($data['epage']) ? 10 : $data['epage'];
        $_sql = "where 1=1";
        if (isset($data['type']) != "") {
            if ($data['type'] == "wait") {
                $_sql .= " and p1.recover_times<p2.borrow_period and p1.user_id={$user_id} and p1.change_status!=1";
            } elseif ($data['type'] == "change") {
                $_sql .= " and p1.recover_account_all!=p1.recover_account_yes and  p1.change_userid={$user_id} and p1.change_status=1";
            } elseif ($data['type'] == "yes") {
                $_sql .= " and p1.recover_times=p2.borrow_period and p1.user_id={$user_id} and p1.change_status!=1";
            }
        }


        if (isset($data['dotime1']) != "") {
            $dotime1 = ($data['dotime1'] == "request") ? $_REQUEST['dotime1'] : $data['dotime1'];
            if (get_mktime($dotime1) != "") {
                $_sql .= " and p1.addtime > " . get_mktime($dotime1);
            }
        }

        if (isset($data['dotime2']) != "") {
            $dotime2 = ($data['dotime2'] == "request") ? $_REQUEST['dotime2'] : $data['dotime2'];
            if (get_mktime($dotime2) != "") {
                $_sql .= " and p1.addtime < " . get_mktime($dotime2);
            }
        }
        if (isset($data['tender_status']) != "") {
            $_sql .= " and p1.status = {$data['tender_status']}";
        }
        if (isset($data['keywords']) != "") {
            $_sql .= " and (p2.`name` like '%" . urldecode($data['keywords']) . "%') ";
        }
        if (isset($data['borrow_status']) != "") {
            $_sql .= " and p2.status = {$data['borrow_status']}";
        }
        if (isset($data['change_status']) != "") {
            $_sql .= " and p1.change_status = {$data['change_status']}";
        }
        if (isset($data['change_userid']) != "") {
            $_sql .= " and p1.change_userid = '{$data['change_userid']}'";
        }
        if (isset($data['user_id']) != "") {
            $_sql .= " and p1.user_id = '{$data['user_id']}'";
        }
        $_select = "p1.id,p1.recover_account_yes,p2.borrow_nid,p2.borrow_nid,p2.name,p2.borrow_apr,p2.user_id,p2.borrow_type,p2.borrow_period,p1.recover_times,p1.account as tender_account,p1.recover_account_wait,p1.user_id as tuser,p2.account as borrow_account,p2.borrow_account_yes,p3.username as borrow_username,p4.credits";

        $sql = "select SELECT from `{borrow_tender}` as p1 left join `{borrow}` as p2 on p1.borrow_nid=p2.borrow_nid left join `{users}` as p3 on p2.user_id=p3.user_id left join `{credit}` as p4 on p2.user_id=p4.user_id {$_sql} ORDER";

        //是否显示全部的信息
        if (isset($data['limit'])) {
            $_limit = "";
            if ($data['limit'] != "all") {
                $_limit = "  limit " . $data['limit'];
            }
            return $mysql->db_fetch_arrays(str_replace(array('SELECT', 'ORDER', 'LIMIT'), array($_select, 'order by p1.`order` desc,p1.id desc', $_limit), $sql));
        }

        $row = $mysql->db_fetch_array(str_replace(array('SELECT', 'ORDER', 'LIMIT'), array("count(*) as  num", "", ""), $sql));

        $total = $row['num'];
        $total_page = ceil($total / $epage);
        $index = $epage * ($page - 1);
        $limit = " limit {$index}, {$epage}";

        $list = $mysql->db_fetch_arrays(str_replace(array('SELECT', 'ORDER', 'LIMIT'), array($_select, 'order by p2.id desc', $limit), $sql));
        $list = $list ? $list : array();
        foreach ($list as $key => $value) {
            $recoversql = "select count(1) as num from `{borrow_repay}` where borrow_nid={$value['borrow_nid']} and (repay_status=1 or repay_web=1)";
            $recoverresult = $mysql->db_fetch_array($recoversql);
            if ($value['borrow_type'] == "day" || $value['borrow_type'] == "roam" || $value['borrow_type'] == "second") {
                $list[$key]['wait_times'] = 1 - $recoverresult['num'];
            } else {
                $list[$key]['wait_times'] = $value['borrow_period'] - $recoverresult['num'];
            }
            $list[$key]["credit"] = borrowClass::GetBorrowCredit(array("user_id" => $value['user_id']));

        }
        return array(
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'epage' => $epage,
            'total_page' => $total_page
        );
    }

    static function GetRecoverVouchList($data = array())
    {
        global $mysql;

        $page = empty($data['page']) ? 1 : $data['page'];
        $epage = empty($data['epage']) ? 10 : $data['epage'];

        $_sql = " where p1.borrow_nid=p2.borrow_nid and p2.user_id=p3.user_id ";
        if (isset($data['borrow_nid']) != "") {
            if ($data['borrow_nid'] == "request") {
                $_sql .= " and p1.borrow_nid= '{$_REQUEST['borrow_nid']}'";
            } else {
                $_sql .= " and p1.borrow_nid= '{$data['borrow_nid']}'";
            }
        }

        if (isset($data['user_id']) != "") {
            $_sql .= " and p2.user_id = '{$data['user_id']}'";
        }

        if (isset($data['vouch_userid']) != "") {
            $_sql .= " and p1.user_id = '{$data['vouch_userid']}'";
        }

        if (isset($data['username']) != "") {
            $_sql .= " and p3.username like '%{$data['username']}%'";
        }

        if (isset($data['type']) == "late") {
            $_sql .= " and p1.repay_time<" . time() . " and p1.status=0";
        }

        if (isset($data['repay_time']) != "") {
            if ($date['repay_time'] <= 0) $data['repay_time'] = time();
            $_repayment_time = get_mktime(date("Y-m-d", $data['repay_time']));
            $_sql .= " and p1.repay_time < '{$_repayment_time}'";
        }

        if (isset($data['dotime2']) != "") {
            $dotime2 = ($data['dotime2'] == "request") ? $_REQUEST['dotime2'] : $data['dotime2'];
            if (get_mktime($dotime2) != "") {
                $_sql .= " and p2.addtime < " . get_mktime($dotime2);
            }
        }
        if (isset($data['dotime1']) != "") {
            $dotime1 = ($data['dotime1'] == "request") ? $_REQUEST['dotime1'] : $data['dotime1'];
            if (get_mktime($dotime1) != "") {
                $_sql .= " and p2.addtime > " . get_mktime($dotime1);
            }
        }

        if (isset($data['status']) != "") {
            $_sql .= " and p1.status in ({$data['status']})";
        }

        if (isset($keywords) != "") {
            if ($keywords == "request") {
                if (isset($_REQUEST['keywords']) && $_REQUEST['keywords'] != "") {
                    $_sql .= " and p2.name like '%" . urldecode($_REQUEST['keywords']) . "%'";
                }
            } else {
                $_sql .= " and p2.name like '%" . $keywords . "%'";
            }

        }

        $_order = " order by p1.id desc";
        if (isset($data['order']) && $data['order'] != "") {
            if ($data['order'] == "repayment_time") {
                $_order = " order by p1.repay_time asc ";
            } elseif ($data['order'] == "order") {
                $_order = " order by p1.order asc ,p1.id desc";
            }
        }

        $_select = " p1.*,p2.name as borrow_name,p2.borrow_period,p3.username as borrow_username";
        $sql = "select SELECT from `{borrow_vouch_recover}` as p1 left join `{borrow}` as p2 on p1.borrow_nid = p2.borrow_nid left join `{users}` as p3 on p3.user_id=p2.user_id {$_sql} ORDER LIMIT";

        //是否显示全部的信息
        if (isset($data['limit'])) {
            $_limit = "";
            if ($data['limit'] != "all") {
                $_limit = "  limit " . $data['limit'];
            }
            $list = $mysql->db_fetch_arrays(str_replace(array('SELECT', 'ORDER', 'LIMIT'), array($_select, $_order, $_limit), $sql));

            foreach ($list as $key => $value) {
                $late = self::LateInterest(array("time" => $value['repay_time'], "account" => $value['reapy_account']));
                if ($value['status'] != 1) {
                    $list[$key]['late_days'] = $late['late_days'];
                    $list[$key]['late_interest'] = $late['late_interest'];
                }
            }
            return $list;
        }

        $row = $mysql->db_fetch_array(str_replace(array('SELECT', 'ORDER', 'LIMIT'), array('count(1) as num', '', ''), $sql));

        $total = $row['num'];
        $total_page = ceil($total / $epage);
        $index = $epage * ($page - 1);
        $limit = " limit {$index}, {$epage}";
        $list = $mysql->db_fetch_arrays(str_replace(array('SELECT', 'ORDER', 'LIMIT'), array($_select, $_order, $limit), $sql));
        $list = $list ? $list : array();
        foreach ($list as $key => $value) {
            $late = self::LateInterest(array("time" => $value['repay_time'], "account" => $value['capital']));
            if ($value['status'] != 1) {
                $list[$key]['late_days'] = $late['late_days'];
                $list[$key]['late_interest'] = $late['late_interest'];
            }
        }
        return array(
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'epage' => $epage,
            'total_page' => $total_page
        );

    }

    /**
     * 投资人数
     *
     * @return Array
     */
    static function GetTenderPeople($data = [])
    {
        global $mysql;
        $sql = 'select count(distinct user_id) total from `{borrow_tender}` where borrow_nid = "' . $data['borrow_nid'] . '"';
        $result = $mysql->db_fetch_array($sql);
        return $result;
    }

    static function addSeal($data)
    {
        global $mysql;
        require_once(ROOT_PATH . "plugins/jzqApi/jzqApi.php");
        $sql = 'select p1.id,p1.pdfname,p1.user_id,p2.realname,p2.card_id,p3.phone 
                from `{borrow_tender}` as p1 left join `{approve_realname}` as p2 on p1.user_id=p2.user_id 
                left join `{users}` as p3 on p1.user_id=p3.user_id 
                where p1.borrow_nid = "' . $data['borrow_nid'] . '"';
        $file = $mysql->db_fetch_arrays($sql);
        foreach ($file as $val) {
            $param = gbkToUtf8(array("name" => $val['realname'], "idCard" => $val['card_id'], "phone" => $val['phone'], "pdfDir" => ROOT_PATH . "data/pdf/seal/" . $val['pdfname'], "pdfpath" => ROOT_PATH . "data/pdf/files/" . $val['pdfname']));
            $jzqApi = new jzqApiClass();
            $res = $jzqApi->getPdfDownload($param);
            if ($res !== true) {
                $sql = 'update `{borrow}` set sealstep=1 where borrow_nid=' . $data['borrow_nid'];
                $mysql->db_query($sql);
                return 1;
            }
        }
        $sql = 'update `{borrow}` set sealstep=2 where borrow_nid=' . $data['borrow_nid'];
        $mysql->db_query($sql);
        return true;
    }

    //上传电子签章相关信息
    static function uploadSignatures($data = array())
    {
        require_once ROOT_PATH . 'modules/approve/approve.class.php';
        global $mysql;
        $sql = 'select pdfname,user_id,id from `{borrow_tender}` where borrow_nid = "' . $data['borrow_nid'] . '"';
        $result = $mysql->db_fetch_arrays($sql);
        $sql = 'select borrow_type from `{borrow}` where borrow_nid = "' . $data['borrow_nid'] . '"';
        $type = $mysql->db_fetch_array($sql);
        foreach ($result as $val) {
            $realname = approveClass::GetRealnameOne(array("user_id" => $val['user_id']));
            if (is_array($realname)) {
                $param = array("user_id" => $val['user_id'], "borrow_nid" => $data['borrow_nid'], "type" => $type['borrow_type'], "realname" => $realname['realname'], "card_id" => $realname['card_id']);
                $file = self::createPDF($param);
                if (!$file) {
                    $sql = 'update `{borrow}` set sealstep=0 where borrow_nid=' . $data['borrow_nid'];
                    $mysql->db_query($sql);
                    return 0;
                } else {
                    $sql = 'update `{borrow_tender}` set pdfname = "' . $file['filename'] . '" where id=' . $val['id'];
                    $mysql->db_query($sql);
                }
            }
        }
        return true;
    }

    static function createPDF($data = array())
    {
        // sleep(10);
        require_once(ROOT_PATH . "modules/borrow/borrow.class.php");
        require_once(ROOT_PATH . "modules/borrow/borrow.tender.php");
        //看情况修改
        $_G['system']['con_template'] = "jglc_new";
        $borrow_nid = $data['borrow_nid'];

        $type = $data['type'];
        $result_head = borrowClass::GetView(array("borrow_nid" => $borrow_nid));

        $result_tender = borrowTenderClass::GetTenderList(array("borrow_nid" => $borrow_nid, "user_id" => $data['user_id'], "limit" => "all"));

        $result_repay = "";
        $protocol = borrowClass::GetProtocol(array("type" => $type));

        $roamdata = "";

        require_once(ROOT_PATH . "libs/pdf.class.php");
        $basePath = ROOT_PATH . "data/pdf/files/";
        !is_dir($basePath) && @mkdir($basePath, 0755, true);

        $cachePath = ROOT_PATH . "data/pdf/cache/";
        !is_dir($cachePath) && @mkdir($cachePath, 0755, true);

        $fileName = $borrow_nid . "_" . $result_tender[0]['id'];
        require_once(ROOT_PATH . "modules/approve/approve.class.php");

        $reverify_time = $result_head['reverify_time'] != 0 ? date('Y年m月d日', $result_head['reverify_time']) : ' 年 月 日';
        $end_time = $result_head['reverify_time'] != 0 ? date('Y年m月d日', $result_head['end_time']) : ' 年 月 日';
        $uinfo = array();
        $uinfo['name'] = '用户服务协议';
        $uinfo['title'] = '（本协议由甲、乙双方' . $reverify_time . '签订）';
        $otherinfo = array('甲方（平台用户）：' . $data['realname'],
            '身份证号码：' . $data['card_id'],
            '乙方：长春井众金融',
            '长春井众金融在此郑重提示您，本文系您与乙方之间 的法律协议，请您认真阅读并理解本协议。本协议在您和乙方之间具有 法律约束力。',
            '本协议适用于乙方所运营“小雨投资”平台“' . $result_head['name'] . '”。',
            '第一条 甲方认购详情',
            '1.1甲方同意按照下列约定认购本项目',
            '认购本金金额：' . $result_tender[0]['account'] . '元',
            '预期年化收益率：' . $result_head['borrow_apr'] . '%',
            '认购期限：' . $result_head['borrow_period_name'],
            '认购期限起始日：' . $reverify_time,
            '认购期限届满日：' . $end_time,
            '1.2还款方式：',
            '购买期限届满日到期一次性还本付息。'
        );
        $jiafang = array("甲方：" . $data['realname'],
            "签订日期：" . $reverify_time);
        $yifang = array("乙方：长春井众金融",
            "签订日期：" . $reverify_time);
        $header = array('出借人', '借款金额', '借款期限', '年利率', '借款开始日', '借款到期日', '', '总还款本息');
        $header0 = array('出借人', '借款金额', '借款期限', '年利率', '借款开始日', '借款到期日', '月截止还款日', '总还款本息'); //设置表头
        $header1 = array('借款期数', '年利率', '应还时间', '还款本息', '还款本金', '还款利息'); //设置表头
        $pdffile = array();
        $pdffile['name'] = $basePath . $fileName . '.pdf';
        //$pdffile['password'] = '51jingang';   //$_G['user_result']['email'];
        if (!empty($result_head['vouch_card_id'])) {
            $pdffile['type'] = 'F'; //D是下载 I是浏览
        } else {
            $pdffile['type'] = 'D'; //D是下载 I是浏览
        }
        $contents = $protocol['contents'];
        // myPDF::creat_newpdf($logo, $uinfo, $otherinfo,$jiafang,$yifang, $contents, $header, $header0, $header1, $pdffile, $type, $_REQUEST['_newtype'], $result_tender, $result_repay, $result_head, $roamdata);
        myPDF::create_mypdf($uinfo, $otherinfo, $jiafang, $yifang, $contents, $pdffile);
        if (!is_file($pdffile['name'])) {
            return false;
        }
        return array("fullname" => $pdffile['name'], "filename" => $fileName . '.pdf');
    }

}
